package com.baichang.taoshunda.service.impl;

import com.baichang.framework.excelption.ServiceException;
import com.baichang.taoshunda.dao.AddressDao;
import com.baichang.taoshunda.dao.CityDao;
import com.baichang.taoshunda.entity.Address;
import com.baichang.taoshunda.service.AddressService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by ${wushenglu} on 17/08/24.
 */
@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private CityDao cityDao;

    /**
     * 查询用户地址
     *
     * @param userId 用户编号
     * @return
     */
    @Override
    public List<Map<String, Object>> getAddressList(int userId) {
        return addressDao.getAddressList(userId);
    }

    /**
     * 添加收货地址
     *  @param userId      用户编号
     * @param address     详细地址
     * @param area        地区
     * @param telephone   手机号
     * @param name        收货人
     * @param isDefault   是否默认   1 默认  0不是默认
     * @param houseNumber
     * @param ulng
     * @param ulat        @return
     * @param cityId
     * @param areaId
     */
    @Override
    public boolean addAddress(int userId, String address, String area, String telephone, String name, int isDefault, String houseNumber, double ulng, double ulat, int cityId, int areaId) throws ServiceException {
//        String ak = "0uvsSrdr5oaZ68dVFyUBCUsK";
        String cityName = area.replace(" ", "").trim();
//        String url = "http://api.map.baidu.com/geocoder/v2/?address=" + cityName + address.trim() + "&output=json&ak=" + ak;
//        String addresspath = null;
//        try {
        if (userId == 0) {
            throw new ServiceException("用户信息异常，请重新登录再试");
        }
//            addresspath = ParserTool.do_get(url);
//            JSONObject jsonObject = JSONObject.fromObject(addresspath);
//            if (jsonObject.get("result") == null) {
//                throw new ServiceException("无法获取到精确位置");
//            }
//            JSONObject result = JSONObject.fromObject(jsonObject.get("result").toString());
//            JSONObject location = JSONObject.fromObject(result.get("location").toString());
//            String lng = location.get("lng").toString();
//            String lat = location.get("lat").toString();
        List<Map<String, Object>> mapList = getAddressList(userId);
        if (mapList == null || mapList.size() == 0) {
            //该用户还没有收货地址，并且新增的地址还不是默认地址，则改为默认地址
            if (isDefault == 0) {
                isDefault = 1;
            }
        } else {
            //如果该用户有收货地址，并且新增的地址设置的还是默认地址，就把他以前的地址设为不是默认地址
            if (isDefault == 1) {
                addressDao.editDeliverAddressIsNoDefalut(userId);
            }
        }
        Address address1 = new Address();
        address1.setUserId(userId);
        address1.setAddress(address.trim());
        address1.setIsDefault(isDefault);
        address1.setHouseNumber(houseNumber);
        address1.setName(name);
        address1.setTelephone(telephone);
        address1.setUlng(ulng);
        address1.setUlat(ulat);
        address1.setArea(cityName);
        address1.setState(1);
        address1.setCityId(cityId);
        address1.setAreaId(areaId);
        return addressDao.save(address1) > 0;
//        } catch (IOException e) {
//            throw new ServiceException("无法获取到精确位置");
//        }

    }

    /**
     * 修改用户地址
     *  @param id          地址编号
     * @param userId      用户编号
     * @param address     详细地址
     * @param area        地区
     * @param telephone   手机号
     * @param name        收货人
     * @param isDefault   是否默认   1 默认  0不是默认
     * @param houseNumber
     * @param ulng
     * @param ulat        @return
     * @param cityId
     * @param areaId
     */
    @Override
    public boolean updateAddress(int id, int userId, String address, String area, String telephone, String name, int isDefault, String houseNumber, double ulng, double ulat, int cityId, int areaId) throws ServiceException {
        if (id == 0) {
            throw new ServiceException("此地址编号有误，请重试");
        }
        if (userId == 0) {
            throw new ServiceException("用户信息异常，请重新登录");
        }
        if (isDefault == 1) {
            addressDao.editDeliverAddressIsNoDefalut(userId);
        }

        return addressDao.updateAddress(userId, address, isDefault, name, telephone, area, id, houseNumber, ulng, ulat,cityId,areaId) > 0;
    }

    /**
     * 删除地址
     *
     * @param id 地址编号
     * @return
     * @throws ServiceException
     */
    @Override
    public boolean deleteDeliveryAddressById(Long id) throws ServiceException {
        if (id == 0) {
            throw new ServiceException("地址信息异常,请稍后重试");
        }
        Address address = addressDao.getEntityById(id);
        if (address == null) {
            throw new ServiceException("地址不存在");
        }
        if (address.getIsDefault() == 1) {
            throw new ServiceException("不能删除默认地址，请先设置其他地址为默认地址再操作！");
        }
        return addressDao.deleteDeliveryAddressById(id);
    }

    /**
     * 修改默认地址
     * 1.把所有地址修改为非默认地址
     * 2.修改对应编号的地址为默认地址
     *
     * @param id     地址编号
     * @param userId 用户编号
     * @return
     */
    @Override
    public boolean updateDefaultAddress(Integer id, Integer userId) throws ServiceException {
        if (userId == 0) {
            throw new ServiceException("用户信息异常，请重新登录再试");
        }
        List<Map<String, Object>> list = addressDao.getAddressList(userId);
//        if (list.size() == 1) {
//            throw new ServiceException("该用户只存在一个地址不支持修改默认地址");
//        }
        addressDao.editDeliverAddressIsNoDefalut(userId);
        return addressDao.updateDefaultAddress(id);
    }

    /**
     * 获取默认地址
     *
     * @param userId 用户编号
     * @return
     */
    @Override
    public Map<String, Object> getDefaultAddress(Integer userId) throws ServiceException {
        Map<String, Object> map = addressDao.getDefaultAddress(userId);
        if (map == null) {
            throw new ServiceException("请先添加地址");
        }
        return map;
    }

    @Override
    public Map<String, Object> getCityIdByName(String cityName, Integer level) {
        Map<String, Object> map = new HashedMap();
        map.put("id", cityDao.getCityIdByName(cityName, level));
        return map;
    }
}
